const { Service } = require('egg');

class BlogService extends Service {
    /**
     * 添加博客
     * @param {object} blog 博客信息
     */
    async create(blog) {
        // 解构参数
        const { title, content, uid } = blog;
        let sql = 'insert into blog (title, content, uid) values (?, ?, ?)';
        let params = [title, content, uid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 读取列表数据
     */
    async readList() {
        let sql = `
            select 
                b.id as bid, b.title, b.content, b.create_time, b.uid, u.username, u.nickname from blog as b
            join user as u on u.id = b.uid
        `;
        let res = await this.app.mysql.query(sql);
        return res;
    }

    /**
     * 根据博客id返回博客详情数据
     * @param {number} id 博客id
     */
    async find(id) {
        let sql = `
            select b.id as bid, b.title, b.content, b.create_time, b.uid, u.username, u.nickname
            from blog as b
                join user as u on b.uid = u.id
            where b.id = ?
        `;
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 修改博客信息
     * @param {object} blog 博客信息
     */
    async update({ id, title, content }) {
        let sql = 'update blog set title = ?, content = ? where id = ?';
        let params = [title, content, id];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }
}

module.exports = BlogService;
